package com.code.ape.codeape.device.api.type.handler;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 公众号：码猿技术专栏
 * @url: www.java-family.cn
 * @description
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class SeparatorToListTypeHandler implements TypeHandler<List<Long>> {

	@Override
	public void setParameter(PreparedStatement preparedStatement, int i, List<Long> parameters, JdbcType jdbcType) throws SQLException {
		if (CollectionUtil.isEmpty(parameters))
			return;
		String res = parameters.stream().map(String::valueOf).collect(Collectors.joining(","));
		preparedStatement.setString(i,res);
	}

	@Override
	public List<Long> getResult(ResultSet resultSet, String columnName) throws SQLException {
		String originRes = resultSet.getString(columnName);
		//转换为List
		return StrUtil.split(originRes, ",").stream().map(Long::parseLong).collect(Collectors.toList());
	}

	@Override
	public List<Long> getResult(ResultSet resultSet, int columnIndex) throws SQLException {
		String originRes = resultSet.getString(columnIndex);
		//转换为List
		return StrUtil.split(originRes, ",").stream().map(Long::parseLong).collect(Collectors.toList());
	}

	@Override
	public List<Long> getResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
		String originRes = callableStatement.getString(columnIndex);
		//转换为List
		return StrUtil.split(originRes, ",").stream().map(Long::parseLong).collect(Collectors.toList());
	}
}
